package com.zhangtai.modules.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.zhangtai.Neusoft.constVo.EmployeeInfoConst;
//import com.zhangtai.Neusoft.service.neuEmployeeBaseInfoService;
import com.zhangtai.Neusoft.service.NeusoftEmployeeChangeService;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.config.AsyncMethod;
import com.zhangtai.exception.QwMsg;
import com.zhangtai.modules.constVo.*;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.common.ContractUrlEntity;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.*;
import com.zhangtai.modules.entity.salary.SalaryChangeEntity;
import com.zhangtai.modules.entity.salary.SalaryDistributionEntity;
import com.zhangtai.modules.entity.system.AuthorityLogEntity;
import com.zhangtai.modules.jobTask.qw.QwUserEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.employee.*;
import com.zhangtai.modules.service.salary.SalaryDistributionService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ming
 * @Date: 2020/6/15 0015 下午 1:36
 */
@Api(tags = "新员工录入接口")
@RestController
@RequestMapping("newEmployees")
@Slf4j
public class EmployessController {
    @Autowired
    private  QwUserDao qwUserDao;
    @Autowired
    private EmployeeInfoService employeeInfoService;

    @Autowired
    private EmployeeInorgnameService employeeInorgnameService;
    @Autowired
    private EmployessSocietyexperienceService employessSocietyexperienceService;
    @Autowired
    private FamilyMemberService familyMemberService;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private ImgUrlDao imgUrlDao;

    @Autowired
    private LoginController loginController;
    @Autowired
    private EmployeeBpmService employeeBpmService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private EmployeeArchiveDao employeeArchiveDao;
    @Autowired
    private EmployeeArchiveService employeeArchiveService;
    @Autowired
    private EmployeeEducationService employeeEducationService;
    @Autowired
    private EmployerCompanyService employerCompanyService;
    //    @Autowired
//    private JobDaoMssql jobDaoMssql;
    @Autowired
    private QwMsg qwMsg;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JobController jobController;
    @Autowired
    private NoticeController noticeController;
    @Autowired
    private ContractUrlDao contractUrlDao;
    @Autowired
    private AuthorityLogDao authorityLogDao;
    @Autowired
    private RelativeRecordsService relativeRecordsService;
    @Autowired
    private RelativeRecordsDao relativeRecordsDao;
    @Autowired
    private EmployeeBpmDao employeeBpmDao;
    @Autowired
    private SalaryDistributionService salaryDistributionService;
    @Autowired
    private SalaryChangeDao salaryChangeDao;
    @Autowired
    private EmployeeChangeController employeeChangeController;
    @Autowired
    private ContractController contractController;
    @Autowired
    private NeusoftEmployeeChangeService neusoftEmployeeChangeService;
    //    @Autowired
//    private ////neuEmployeeBaseInfoService ////neuEmployeeBaseInfoService;
    @Autowired
    private BaseMssqlServiceImpl baseMssqlServiceImpl;
    @Autowired
    private AsyncMethod asyncMethod;
    @Autowired
    private InternalAwardDao internalAwardDao;
    @Autowired
    private InternalAwardService internalAwardService;

    @Autowired
    private EmployeeRecruitmentDao employeeRecruitmentDao;
    @Autowired
    private EmployeeRecruitmentService employeeRecruitmentService;

    /**
     * 查询所有的员工信息
     * pageNum
     * 1
     * pageSize
     * 20
     * current
     * 1
     *
     * @return
     */
    @GetMapping("/getEmployeeInfoPage")
    public R getAllEmployeeInfo(
            @RequestParam(value = "orgname", required = false) String orgname,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "unitname", required = false) String unitname,
            @RequestParam(value = "jobname", required = false) String jobname,
            @RequestParam("pageNum") String pageNum,
            @RequestParam("pageSize") String pageSize,
            @RequestParam("current") String current
    ) {
        PageUtils page = employeeInfoService.getAllEmployeeInfos(orgname, name, unitname, pageNum, pageSize, current, jobname);

        return R.ok(page);
    }
/*
    @PostMapping("/list")
    @ApiOperation(value = "招聘台账列表，查询所有员工")
    @PreAuthorize("hasAuthority('emp:zp:get')")
    public R<PageResult<EmployeeInfoDto>> queryPage(@RequestBody @Valid EmployeeListDto employeeListDto,
                                                    HttpServletRequest request) throws Exception {
//        log.info("employeeListDto:{}",employeeListDto);

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> selectOrg = null;
        List<Long> selectUnit = null;
        List<Long> selectJob = null;
        //null未查询，size为0查询结果为空
        if (!StringUtils.isEmpty(employeeListDto.getOrgname())) {
            selectOrg = jobDaoMssql.findOrgByName(employeeListDto.getOrgname());
            if (selectOrg == null) {
                selectOrg = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(employeeListDto.getUnitname())) {
            selectUnit = jobDaoMssql.findOrgByName(employeeListDto.getUnitname());
            if (selectUnit == null) {
                selectUnit = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(employeeListDto.getJobname())) {
            selectJob = jobDaoMssql.findJobIdByName(employeeListDto.getJobname());
            if (selectJob == null) {
                selectJob = new ArrayList<>();
            }
        }

        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String code = user.getString("usercode");
        //当前日期
//        String date= DateUtils.format(new Date(),"yyyy-MM-dd")+" 23:59:59";
//        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.queryPage(employeeOid,name,orgname,unitname,jobname,keyword, status,isReinstate,isEntryStatus,pageNum,pageSize,orgIds);
        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.queryPage(employeeListDto.getEmployeeOid(), employeeListDto.getName(),
                selectOrg, selectUnit, selectJob,
                employeeListDto.getStatus(), employeeListDto.getIsReinstate(), employeeListDto.getIsEntryStatus(),
                employeeListDto.getPageNum(), employeeListDto.getPageSize(), orgIds, employeeListDto.getSocialTrainee(),
                employeeListDto.getIsOffer(), employeeListDto.getIsSendContract(), code);
        List<EmployeeInfoEntity> list = pageResult.getList();
        ArrayList<EmployeeInfoDto> infoDtoList = new ArrayList<>();

        for (EmployeeInfoEntity infoEntity : list) {
            Long orgId = infoEntity.getOrgId();
            Long unitId = infoEntity.getUnitId();
            Long jobId = infoEntity.getJobId();
            Long jobLevelId = infoEntity.getJobLevelId();

//            根据id去换缓存中获取组织名称
            String orgName = jobController.getOrgNameById(orgId);
            String unitName = jobController.getOrgNameById(unitId);
            //根据id去换缓存中获取岗位名称
            String jobName = jobController.getJobName(jobId);

            //根据id去换缓存中获取职级名称
            String jobLevelName = jobController.getJobLevelNameById(jobLevelId);


            EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(infoEntity, EmployeeInfoDto.class);


            employeeInfoDto.setOrgname(orgName);
            employeeInfoDto.setUnitname(unitName);
            employeeInfoDto.setJobname(jobName);
            employeeInfoDto.setJobLevel(jobLevelName);

            //查询修改入职记录
            if (employeeListDto.getIsShowAuthorityLog()) {
                List<AuthorityLogEntity> authorityLogEntity = authorityLogDao.selectList(new QueryWrapper<AuthorityLogEntity>()
                        .eq("is_delete", "0")
                        .eq("oid", infoEntity.getOid())
                        .eq("type", 1)
                        .orderByDesc("update_time"));
                if (!CollectionUtils.isEmpty(authorityLogEntity)) {
                    AuthorityLogEntity entity = authorityLogEntity.get(0);
                    employeeInfoDto.setUpdateEntryStr("修改人：" + entity.getUpdateUserName() + "，修改前入职日期:" + entity.getOldData());
                }

            }
            infoDtoList.add(employeeInfoDto);

        }
        PageResult<EmployeeInfoDto> result = new PageResult<>();
        result.setList(infoDtoList);
        result.setCurrPage(pageResult.getCurrPage());
        result.setPageSize(pageResult.getPageSize());
        result.setTotalCount(pageResult.getTotalCount());
        result.setTotalPage(pageResult.getTotalPage());
        return R.ok(result);
    }
*/
  /*  @GetMapping("/list/{query}")
    public R<PageResult<>>*/

    @PostMapping("/list")
    @ApiOperation(value = "招聘台账列表，查询所有员工")
    @PreAuthorize("hasAuthority('emp:zp:get')")
    public R<PageResult<EmployeeInfoDto>> queryPage(@RequestBody @Valid EmployeeListDto employeeListDto,
                                                    HttpServletRequest request) throws Exception {
//        log.info("employeeListDto:{}",employeeListDto);

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> selectOrg = null;
        List<Long> selectUnit = null;
        List<Long> selectJob = null;
        //null未查询，size为0查询结果为空
        if (!StringUtils.isEmpty(employeeListDto.getOrgname())) {
//            selectOrg = jobDaoMssql.findOrgByName(employeeListDto.getOrgname());
            if (selectOrg == null) {
                selectOrg = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(employeeListDto.getUnitname())) {
//            selectUnit = jobDaoMssql.findOrgByName(employeeListDto.getUnitname());
            if (selectUnit == null) {
                selectUnit = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(employeeListDto.getJobname())) {
//            selectJob = jobDaoMssql.findJobIdByName(employeeListDto.getJobname());
            if (selectJob == null) {
                selectJob = new ArrayList<>();
            }
        }

        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String code = user.getString("usercode");
        //当前日期
//        String date= DateUtils.format(new Date(),"yyyy-MM-dd")+" 23:59:59";
//        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.queryPage(employeeOid,name,orgname,unitname,jobname,keyword, status,isReinstate,isEntryStatus,pageNum,pageSize,orgIds);
        PageResult<EmployeeRecruitmentEntity> pageResult = employeeRecruitmentService.queryPage(employeeListDto.getName(),
                selectOrg, selectUnit, selectJob,
                employeeListDto.getStatus(), employeeListDto.getIsEntryStatus(),
                employeeListDto.getPageNum(), employeeListDto.getPageSize(), orgIds, employeeListDto.getSocialTrainee(),
                employeeListDto.getIsOffer(), employeeListDto.getIsSendContract(), code);
        List<EmployeeRecruitmentEntity> list = pageResult.getList();
        ArrayList<EmployeeInfoDto> infoDtoList = new ArrayList<>();

        for (EmployeeRecruitmentEntity infoEntity : list) {
            Long orgId = infoEntity.getOrgId();
            Long unitId = infoEntity.getUnitId();
            Long jobId = infoEntity.getJobId();
            Long jobLevelId = infoEntity.getJobLevelId();

//            根据id去换缓存中获取组织名称
            String orgName = jobController.getOrgNameById(orgId);
            String unitName = jobController.getOrgNameById(unitId);
            //根据id去换缓存中获取岗位名称
            String jobName = jobController.getJobName(jobId);

            //根据id去换缓存中获取职级名称
            String jobLevelName = jobController.getJobLevelNameById(jobLevelId);


            EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(infoEntity, EmployeeInfoDto.class);


            employeeInfoDto.setOrgname(orgName);
            employeeInfoDto.setUnitname(unitName);
            employeeInfoDto.setJobname(jobName);
            employeeInfoDto.setJobLevel(jobLevelName);

            //查询修改入职记录
            if (employeeListDto.getIsShowAuthorityLog()) {
                List<AuthorityLogEntity> authorityLogEntity = authorityLogDao.selectList(new QueryWrapper<AuthorityLogEntity>()
                        .eq("is_delete", "0")
                        .eq("oid", infoEntity.getOid())
                        .eq("type", 1)
                        .orderByDesc("update_time"));
                if (!CollectionUtils.isEmpty(authorityLogEntity)) {
                    AuthorityLogEntity entity = authorityLogEntity.get(0);
                    employeeInfoDto.setUpdateEntryStr("修改人：" + entity.getUpdateUserName() + "，修改前入职日期:" + entity.getOldData());
                }

            }
            infoDtoList.add(employeeInfoDto);

        }
        PageResult<EmployeeInfoDto> result = new PageResult<>();
        result.setList(infoDtoList);
        result.setCurrPage(pageResult.getCurrPage());
        result.setPageSize(pageResult.getPageSize());
        result.setTotalCount(pageResult.getTotalCount());
        result.setTotalPage(pageResult.getTotalPage());
        return R.ok(result);
    }


    @GetMapping("/getEmployeeById/{id}")
    @ApiOperation(value = "根据员工id获取详情(从现有库中查询)")
    @PreAuthorize("hasAuthority('emp:zp:get')")
    // @SysLog(value ="测试[{{id}}]备份",operationType = OperationType.SELECT)
    public R<EmployeeInfoDto> findEmployeeByOid(@PathVariable("id") Long id) {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(id);
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.ok();
        }
        Long oid = employeeInfoEntity.getOid();

        List<EmployeeEducationEntity> educationEntities = employeeEducationService.findEmployeeEducationListByOid(oid);
        List<EmployeeInorgnameEntity> inorgnameEntityList = employeeInorgnameService.getByEmpId(oid);
//        log.info("政治面貌:{}",inorgnameEntityList);
        List<EmployessSocietyexperienceEntity> societyexperienceEntities = employessSocietyexperienceService.getByEmpId(oid);
        //查询员工合同记录
        List<ContractUrlEntity> contractList = contractUrlDao.selectList(new QueryWrapper<ContractUrlEntity>().eq("is_delete", 0).eq("id_card", employeeInfoEntity.getIdcard()).isNotNull("contract_oss_url"));
        List<FamilyMemberEntity> familyMemberEntities = familyMemberService.getListByEmpId(oid);
//        亲属报备
        List<RelativeRecordsEntity> relativeRecordsEntities = relativeRecordsDao.selectList(new QueryWrapper<RelativeRecordsEntity>().eq("oid", oid).eq("is_delete", 0));

        EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeInfoDto.class);
        employeeInfoDto.setEmployeeEducation(educationEntities);
        employeeInfoDto.setEmployeeInorgname(inorgnameEntityList);
        employeeInfoDto.setFamilyMember(familyMemberEntities);
        employeeInfoDto.setEmployeeSociety(societyexperienceEntities);
        employeeInfoDto.setContractList(contractList);
        employeeInfoDto.setRelativeRecordsEntities(relativeRecordsEntities);

        getImg(oid, employeeInfoDto); //封装图片

        setParam(employeeInfoEntity, employeeInfoDto); //封装名称

        Long employerCompanyId = employeeInfoEntity.getEmployerCompanyId();
        EmployerCompanyEntity byIdE = employerCompanyService.getByIdE(employerCompanyId);
        if (!ObjectUtils.isEmpty(byIdE)) {
            //        封装甲方单位
            employeeInfoDto.setEmployerCompany(byIdE.getName());
        }

//        封装复职员工信息
        Integer isReinstate = employeeInfoEntity.getIsReinstate(); //0:新员工，1：复职员工，2：旧员工,3:离职超过一年
        Integer i = 1;
        Integer k = 3;
        if (i.equals(isReinstate) || k.equals(isReinstate)) {
            EmployeeBpmEntity employeeBpmEntity = employeeBpmService.getByIdE(oid);
            if (!ObjectUtils.isEmpty(employeeBpmEntity)) {
                OldEmployeeDto oldEmployeeDto = BeanUtilsMabach.doToDto(employeeBpmEntity, OldEmployeeDto.class);
                employeeInfoDto.setOldEmployeeDto(oldEmployeeDto);
            }
        }
        EmployeeBpmEntity employeeBpmEntity = employeeBpmService.getByIdE(id);
        if (!ObjectUtils.isEmpty(employeeBpmEntity)) {
            employeeInfoDto.setIsRemoteSocialSecurity(employeeBpmEntity.getIsRemoteSocialSecurity());
            employeeInfoDto.setSocialSecurityCity(employeeBpmEntity.getSocialSecurityCity());
            employeeInfoDto.setSocialSecurityProvince(employeeBpmEntity.getSocialSecurityProvince());
        }

        return R.ok(employeeInfoDto);
    }

    private void setParam(EmployeeInfoEntity employeeInfoEntity, EmployeeInfoDto employeeInfoDto) {
        /**
         * 根据各种id查询名称
         */
        Long unitId = employeeInfoEntity.getUnitId();
        Long orgId = employeeInfoEntity.getOrgId();
        Long jobId = employeeInfoEntity.getJobId();

        Long jobSystemId = employeeInfoEntity.getJobSystemId();
        Long lineId = employeeInfoEntity.getLineId();


        Long jobLevelId = employeeInfoEntity.getJobLevelId();
        String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
        employeeInfoDto.setJobLevel(jobLevelNameById);


        String systemNameById = jobController.getSystemNameById(jobSystemId);
//        log.info("OrgSystemEntity:{}",jobLevelById);

        employeeInfoDto.setJobSystem(systemNameById);

        String lineNameById = jobController.getLineNameById(lineId);

        employeeInfoDto.setLine(lineNameById);


        String org = jobController.getOrgNameById(orgId);
        employeeInfoDto.setOrgname(org);


        String unit = jobController.getOrgNameById(unitId);
        employeeInfoDto.setUnitname(unit);


        String jobName = jobController.getJobName(jobId);
        employeeInfoDto.setJobname(jobName);
    }


    @PostMapping("/saveMainInfo")
    @ApiOperation(value = "添加新员工主体信息")
    @SysAuthorityLog(value = "添加新员工主体信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:zp:update')")
    public R saveMainInfo(@RequestBody @Valid EmployeeInfoVo employeeInfoVo, HttpServletRequest request) throws Exception {
//        log.info("==================>>>>>参数：{}",employeeInfoVo);
        Boolean flag = false;
        String idcard = employeeInfoVo.getIdcard().trim();
        List<EmployeeInfoEntity> employeeInfoEntities = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("idcard", idcard).eq("is_delete", 0));
        if (!CollectionUtils.isEmpty(employeeInfoEntities)) {
            return R.error("身份证为" + idcard + "的录已经存在");
        }
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(employeeInfoVo, EmployeeInfoEntity.class);
        employeeInfoEntity.setIdcard(idcard);
        String mobile = employeeInfoVo.getMobile().trim();
        employeeInfoEntity.setMobile(mobile);
        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
        Long id = null;


        if (CollectionUtils.isEmpty(employeeInfoEntities)) {
            id = snowflakeIdWorker.nextId();
        } else {
            EmployeeInfoEntity emp = employeeInfoEntities.get(0);
            id = emp.getOid();
        }
        Long oid = employeeInfoVo.getOid();
        if (oid != null) {
            id = oid;
        }


        employeeInfoEntity.setOid(id);


        Date date = new Date();
//        插入时间
        employeeInfoEntity.setInsetDate(date);
//        插入编号
        employeeInfoEntity.setEmployeeOid(Long.parseLong(getUserCode()));

//        封装图片
        setImg(employeeInfoVo, id);

        String uuid = UUID.randomUUID().toString().replace("-", "");
        employeeInfoEntity.setToken(uuid);
        employeeInfoEntity.setOperatetime(new Date());


        employeeInfoEntity.setIsDistribute(0);
        employeeInfoEntity.setDealStatus(0);
        employeeInfoEntity.setIsEntryStatus(0);
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        String name = userInfo.getString("name");
        String usercode = userInfo.getString("usercode");
        employeeInfoEntity.setPrincipalUserCode(usercode); //设置管理员、负责人工号
        employeeInfoEntity.setPrincipal(name);
        employeeInfoEntity.setIsReinstate(employeeInfoVo.getIsReinstate());//0:新员工，1：复职员工，2:老员工

        String socialTrainee = employeeInfoVo.getSocialTrainee();  //0：社招，1：实习生
        if ("1".equals(socialTrainee)) {
            employeeInfoEntity.setEmployeestatus("9");  //员工状态，9：实习

        } else {
            //  employeeInfoEntity.setEmployeestatus("2"); //员工状态，2：在职，9：实习，3,4,5,6：离职
            employeeInfoEntity.setEmployeestatus("0"); //员工状态，2：在职，9：实习，3,4,5,6：离职
        }
        Integer probationday = employeeInfoVo.getProbationday(); //试用期
        Date hiredate = employeeInfoVo.getHiredate();
        if (probationday != null && hiredate != null) {
            Date reguDate = DateUtils.addDateMonths(hiredate, probationday);
            Date date1 = DateUtils.addDateDays(reguDate, -1);
            employeeInfoEntity.setRegularDay(date1);
        }

        employeeInfoEntity.setCreateTime(new Date());
        employeeInfoEntity.setUpdateTime(new Date());

        EmployeeBpmEntity employeeBpmEntity = BeanUtilsMabach.doToDto(employeeInfoVo, EmployeeBpmEntity.class);
        employeeBpmEntity.setOid(id);

        employeeBpmEntity.setApplyName(name);
        employeeBpmEntity.setApplyUserCode(usercode);

        employeeBpmEntity.setCreateTime(new Date());
        employeeBpmEntity.setUpdateTime(new Date());
//        setJobLevel(employeeInfoVo, employeeInfoEntity); //根据管理职级是否为空来设置职级


        employeeInfoEntity.setCreateTime(new Date());
        Integer type = employeeInfoVo.getType();
        Integer o = 1;
        Integer p = 2;
        if (o.equals(type)) {
            employeeInfoEntity.setIsReinstate(1); //1：离职未超过一年
        } else if (p.equals(type)) {
            employeeInfoEntity.setIsReinstate(3); //离职超过一年
        } else {
            employeeInfoEntity.setIsReinstate(0); //0：新员工  默认为2：老员工
        }

        //保存 招聘数据表
        EmployeeRecruitmentEntity employeeRecruitmentEntity = BeanUtilsMabach.doToDto(employeeInfoVo, EmployeeRecruitmentEntity.class);
        employeeRecruitmentEntity.setOid(id);
        employeeRecruitmentEntity.setEmployeeOid(employeeInfoEntity.getEmployeeOid());
        employeeRecruitmentEntity.setCreateTime(new Date());
        employeeRecruitmentEntity.setPrincipal(name);
        employeeRecruitmentEntity.setIsEntryStatus(0);
        employeeRecruitmentEntity.setEmployeestatus(employeeInfoEntity.getEmployeestatus()); //员工状态，2：在职，9：实习，3,4,5,6：离职
        employeeRecruitmentEntity.setRegularDay(employeeInfoEntity.getRegularDay());
        employeeRecruitmentEntity.setIsReinstate(employeeInfoEntity.getIsReinstate());
        employeeRecruitmentEntity.setPrincipalUserCode(usercode);
        employeeRecruitmentDao.insert(employeeRecruitmentEntity);
        employeeInfoEntity.setRecruitmentId(employeeRecruitmentEntity.getId());


        if (CollectionUtils.isEmpty(employeeInfoEntities)) {
            employeeInfoService.saveE(employeeInfoEntity);
            employeeBpmService.saveE(employeeBpmEntity);
        } else {
            employeeInfoService.updateByIdE(employeeInfoEntity);
            employeeBpmService.updateByIdE(employeeBpmEntity);
        }
//        asyncMethod.saveEmployeeInfoSchedule(employeeInfoEntity.getCode(), employeeInfoEntity.getOid());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id + "");
        flag = true;
        //发送录用待办给负责人
        try {
            sendNewEmployeeToDo(employeeInfoEntity, usercode);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e + "");
        }
        if (flag) {
            /**
             * 用队列处理业务，获取ehr的工号并写入到本地库里
             */

//            messageSender.send(GetUserCodeMqConfig.SMS_EXCHANGE,GetUserCodeMqConfig.SMS_ROUTING_KEY,id+"");
            return R.ok(jsonObject);
        }

        return R.error();
    }


    @PostMapping("/updateNewMainInfo")
    @ApiOperation(value = "如果本地库已存在并且是离职状态则走这个方法")
    @SysAuthorityLog(value = "修改新员工主体信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:zp:update')")
    public R updateNewMainInfo(@RequestBody @Valid EmployeeInfoVo employeeInfoVo, HttpServletRequest request) throws Exception {

        Boolean flag = false;
        String idcard = employeeInfoVo.getIdcard();
        List<EmployeeInfoEntity> employeeInfoEntities = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("idcard", idcard).eq("is_delete", 0));
        EmployeeInfoEntity entity = employeeInfoEntities.get(0);
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(employeeInfoVo, EmployeeInfoEntity.class);
        employeeInfoEntity.setIdcard(idcard);
        String mobile = employeeInfoVo.getMobile().trim();
        employeeInfoEntity.setMobile(mobile);
        Long id = entity.getOid();


        employeeInfoEntity.setOid(id);
        Date date = new Date();
//        插入时间
        employeeInfoEntity.setInsetDate(date);
//        插入编号
        employeeInfoEntity.setEmployeeOid(Long.parseLong(getUserCode()));

//        封装图片
        setImg(employeeInfoVo, id);

        String uuid = UUID.randomUUID().toString().replace("-", "");
        employeeInfoEntity.setToken(uuid);
        employeeInfoEntity.setOperatetime(new Date());


        employeeInfoEntity.setIsDistribute(0);
        employeeInfoEntity.setDealStatus(0);
        employeeInfoEntity.setIsEntryStatus(0);
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(userInfo)) {
            return R.error("请先登录");
        }
        String name = userInfo.getString("name");
        String usercode = userInfo.getString("usercode");
        employeeInfoEntity.setPrincipalUserCode(usercode); //设置管理员、负责人工号
        employeeInfoEntity.setPrincipal(name);
        employeeInfoEntity.setIsReinstate(employeeInfoVo.getIsReinstate());//0:新员工，1：复职员工，2:老员工

        String socialTrainee = employeeInfoVo.getSocialTrainee();  //0：社招，1：实习生
        if ("1".equals(socialTrainee)) {
            employeeInfoEntity.setEmployeestatus("9");  //员工状态，9：实习

        } else {
            // employeeInfoEntity.setEmployeestatus("2"); //员工状态，2：在职，9：实习，3,4,5,6：离职
            employeeInfoEntity.setEmployeestatus("0"); //员工状态，2：在职，9：实习，3,4,5,6：离职
        }
        Integer probationday = employeeInfoVo.getProbationday(); //试用期
        Date hiredate = employeeInfoVo.getHiredate();

        if (probationday != null && hiredate != null) {
            Date reguDate = DateUtils.addDateMonths(hiredate, probationday);
            employeeInfoEntity.setRegularDay(reguDate);
        }
        employeeInfoEntity.setCreateTime(new Date());
        employeeInfoEntity.setUpdateTime(new Date());


        EmployeeBpmEntity employeeBpmEntity = BeanUtilsMabach.doToDto(employeeInfoVo, EmployeeBpmEntity.class);
        employeeBpmEntity.setOid(id);

        employeeBpmEntity.setApplyName(name);
        employeeBpmEntity.setApplyUserCode(usercode);

        employeeBpmEntity.setCreateTime(new Date());
        employeeBpmEntity.setUpdateTime(new Date());
//        setJobLevel(employeeInfoVo, employeeInfoEntity); //根据管理职级是否为空来设置职级


        employeeInfoEntity.setCreateTime(new Date());
        Integer type = employeeInfoVo.getType();
        Integer o = 1;
        Integer p = 2;
        if (o.equals(type)) {
            employeeInfoEntity.setIsReinstate(1); //1：离职未超过一年
        } else if (p.equals(type)) {
            employeeInfoEntity.setIsReinstate(3); //离职超过一年
        } else {
            employeeInfoEntity.setIsReinstate(0); //0：新员工  默认为2：老员工
        }
        //保存 招聘数据表
        EmployeeRecruitmentEntity employeeRecruitmentEntity = BeanUtilsMabach.doToDto(employeeInfoVo, EmployeeRecruitmentEntity.class);
        employeeRecruitmentEntity.setOid(id);
        employeeRecruitmentEntity.setEmployeeOid(employeeInfoEntity.getEmployeeOid());
        employeeRecruitmentEntity.setCreateTime(new Date());
        employeeRecruitmentEntity.setPrincipal(name);
        employeeRecruitmentEntity.setIsEntryStatus(0);
        employeeRecruitmentEntity.setEmployeestatus(employeeInfoEntity.getEmployeestatus()); //员工状态，2：在职，9：实习，3,4,5,6：离职
        employeeRecruitmentEntity.setRegularDay(employeeInfoEntity.getRegularDay());
        employeeRecruitmentEntity.setIsReinstate(employeeInfoEntity.getIsReinstate());
        employeeRecruitmentEntity.setPrincipalUserCode(usercode);
        employeeRecruitmentDao.insert(employeeRecruitmentEntity);
        employeeInfoEntity.setRecruitmentId(employeeRecruitmentEntity.getId());

        employeeInfoService.updateByIdE(employeeInfoEntity);
        //异步初始化员工招聘信息
        asyncMethod.initializationEmployeeInfo(employeeBpmEntity.getOid());
        //
//        asyncMethod.saveEmployeeInfoSchedule(employeeInfoEntity.getCode(), employeeInfoEntity.getOid());
        List<EmployeeBpmEntity> employeeBpmEntities = employeeBpmDao.selectList(new QueryWrapper<EmployeeBpmEntity>().eq("oid", id).eq("is_delete", 0));

        if (CollectionUtils.isEmpty(employeeBpmEntities)) {
            employeeBpmEntity.setOid(id);
            employeeBpmService.saveE(employeeBpmEntity);
        } else {
            employeeBpmService.updateByIdE(employeeBpmEntity);
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id + "");
        flag = true;
        //发送录用待办给负责人
        try {
            sendNewEmployeeToDo(employeeInfoEntity, usercode);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e + "");
        }
        if (flag) {
            return R.ok(jsonObject);
        }
        return R.error();
    }


    @PostMapping("/updateMainInfo")
    @ApiOperation(value = "修改新员工主体信息")
    @SysAuthorityLog(value = "修改新员工主体信息")
//    @Transactional
    @PreAuthorize("hasAuthority('emp:zp:update')")
    public R updateMainInfo(@RequestBody EmployeeInfoUpdateVo employeeInfoUpdateVo, HttpServletRequest request) throws Exception {
        Boolean flag = false;
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(employeeInfoUpdateVo, EmployeeInfoEntity.class);
        String idcard = employeeInfoUpdateVo.getIdcard().trim();
        employeeInfoEntity.setIdcard(idcard);
        String mobile = employeeInfoUpdateVo.getMobile().trim();
        employeeInfoEntity.setMobile(mobile);
        if (!ObjectUtils.isEmpty(employeeInfoUpdateVo.getNativeplace())) {
            employeeInfoEntity.setNativeplace(employeeInfoUpdateVo.getNativeplace().toString());
        }
//        if (!ObjectUtils.isEmpty(employeeInfoUpdateVo.getNativeplaceProvince())) {
//            employeeInfoEntity.setNativeplaceProvince(employeeInfoUpdateVo.getNativeplaceProvince().toString());
//        }
        employeeInfoEntity.setOperatetime(new Date());
        employeeInfoEntity.setUpdateTime(new Date());
        //        封装图片
        updateImg(employeeInfoUpdateVo);

        Date hiredate = employeeInfoUpdateVo.getHiredate();
        if (hiredate != null && !ObjectUtils.isEmpty(employeeInfoUpdateVo.getProbationday())) {
            Integer probationday = employeeInfoUpdateVo.getProbationday(); //试用期
            Date reguDate = DateUtils.addDateMonths(hiredate, probationday);
            employeeInfoEntity.setRegularDay(reguDate);
        }

        EmployeeBpmEntity employeeBpmEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeBpmEntity.class);
        employeeBpmEntity.setUpdateTime(new Date());

        //修改招聘数据信息
        EmployeeInfoEntity entity = employeeInfoService.getByIdE(employeeInfoEntity.getOid());
        if (!StringUtils.isEmpty(entity.getRecruitmentId())) {
            EmployeeRecruitmentEntity employeeRecruitmentEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeRecruitmentEntity.class);
            employeeRecruitmentEntity.setId(entity.getRecruitmentId());
            employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
        }

        employeeBpmService.updateByIdE(employeeBpmEntity);
        employeeInfoService.updateByIdE(employeeInfoEntity);

        EmployeeInfoEntity employeeInfo = employeeInfoService.getByIdE(employeeBpmEntity.getOid());

        //同步到ehr
//        ////neuEmployeeBaseInfoService.saveEmpBaseInfo(employeeInfoEntity.getOid());

        //查看是否是录用BPM审批中过且入职日期有变更
        if (!ObjectUtils.isEmpty(employeeInfo) && EmployeeConst.EMPLOYEE_STATUS_PASSED.equals(employeeInfo.getStatus())
                && !ObjectUtils.isEmpty(employeeInfo.getHiredate())
                && !employeeInfo.getHiredate().equals(employeeInfoEntity.getHiredate())) {
            //将之前的待办信息置为已读
            noticeController.updateNoticeTodo(employeeInfoEntity.getOid(), NoticeConst.TODO_TYPE_NEW_EMPLOYEE);
            //发送新的待办信息
            sendHireToDo(employeeInfoEntity);
        }

        flag = true;
        if (flag) {
            return R.ok();
        }

        return R.error();
    }


    @GetMapping("/isNewOrReinstate/{idCard}")
    @ApiOperation(value = "根据身份证判断是新员工还是复职")
    @PreAuthorize("hasAuthority('emp:zp:get')")
    public R<OldEmployeeEntity> isNewOrReinstate(@PathVariable("idCard") String idCard) {
//        先去查询本地库，如果有则返回最新的那条

        log.info("idCard:{}", idCard);
        OldEmployeeEntity oldEmployeeEntity = new OldEmployeeEntity();

        //查询归档信息
        List<EmployeeArchiveEntity> employeeArchiveEntityList = employeeArchiveDao.selectList(new QueryWrapper<EmployeeArchiveEntity>().eq("idcard", idCard)
                .eq("is_delete", 0).orderByDesc("update_time"));
        if (!CollectionUtils.isEmpty(employeeArchiveEntityList)) {
            oldEmployeeEntity = BeanUtilsMabach.doToDto(employeeArchiveEntityList.get(0), OldEmployeeEntity.class);
            oldEmployeeEntity.setType(3); //黑名单
            oldEmployeeEntity.setArchiveNum(employeeArchiveEntityList.size());
            if (employeeArchiveEntityList != null && employeeArchiveEntityList.size() != 0) {
                oldEmployeeEntity.setArchiveTime(employeeArchiveEntityList.get(0).getUpdateTime());
            }
            return R.ok(oldEmployeeEntity);
        } else {
//            查询本地
            List<EmployeeInfoEntity> employeeInfoEntitys = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("idcard", idCard)
                    .eq("is_delete", 0));

            if (!CollectionUtils.isEmpty(employeeInfoEntitys)) {
                EmployeeInfoEntity employeeInfoEntity = employeeInfoEntitys.get(0);
                oldEmployeeEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, OldEmployeeEntity.class);

                String socialTrainee = employeeInfoEntity.getSocialTrainee();

                String employeestatus = oldEmployeeEntity.getEmployeestatus();


                if ("2".equals(employeestatus)) {
                    oldEmployeeEntity.setOldhiredate(employeeInfoEntity.getHiredate());
                    oldEmployeeEntity.setType(0); //本地库已有,并且是新员工
                }
//                如果是离职员工
                if (!"2".equals(employeestatus) && !"9".equals(employeestatus)) {
                    Date dimissionTime = employeeInfoEntity.getDimissionTime();
                    if (dimissionTime != null) {
                        Integer daysBetween = DateUtils.daysBetween(dimissionTime, new Date());
                        oldEmployeeEntity.setDaysBetween(daysBetween);
                        oldEmployeeEntity.setOldhiredate(oldEmployeeEntity.getHiredate());
                        oldEmployeeEntity.setDimissiondate(dimissionTime);
                        if (daysBetween != null && daysBetween < 365) {
                            oldEmployeeEntity.setType(1);  //离职没超过一年
                            oldEmployeeEntity.setIsUpdate(1);
                        } else if (daysBetween != null && daysBetween >= 365) {
                            oldEmployeeEntity.setType(2); //离职超过一年
                            oldEmployeeEntity.setIsUpdate(1);
                        }
                    }

                }

                if ("1".equals(socialTrainee)) {
                    oldEmployeeEntity.setOldhiredate(employeeInfoEntity.getHiredate());
                    oldEmployeeEntity.setType(9);  //实习生
//                   如果是离职状态，还要封装离职天数
                    if (!"9".equals(employeestatus)) {
                        Date dimissionTime = employeeInfoEntity.getDimissionTime();
                        if (dimissionTime != null) {
                            Integer daysBetween = DateUtils.daysBetween(dimissionTime, new Date());
                            oldEmployeeEntity.setDaysBetween(daysBetween);
                            oldEmployeeEntity.setDimissiondate(dimissionTime);
                            if (daysBetween != null && daysBetween < 365) {
                                oldEmployeeEntity.setType(1);  //离职没超过一年
                            } else if (daysBetween != null && daysBetween >= 365) {
                                oldEmployeeEntity.setType(2); //离职超过一年
                            }
                        }
                    }
                }
                Long orgId = oldEmployeeEntity.getOrgId();
                String orgNameById = jobController.getOrgNameById(orgId);
                oldEmployeeEntity.setOrgname(orgNameById);
                Long unitId = oldEmployeeEntity.getUnitId();
                String unitname = jobController.getOrgNameById(unitId);
                oldEmployeeEntity.setUnitname(unitname);
                Long jobId = oldEmployeeEntity.getJobId();
                String jobName = jobController.getJobName(jobId);
                oldEmployeeEntity.setJobname(jobName);


                return R.ok(oldEmployeeEntity);
            }
        }
//如果本地库没有，则去sqlServer查询
        oldEmployeeEntity = findEmpByIdcard(idCard);
        if (ObjectUtils.isEmpty(oldEmployeeEntity)) {

            return R.ok();
        }

        Integer daysBetween = oldEmployeeEntity.getDaysBetween();

        if (daysBetween != null && daysBetween < 365) {
            oldEmployeeEntity.setType(1);  //离职没超过一年
        } else if (daysBetween != null && daysBetween >= 365) {
            oldEmployeeEntity.setType(2); //离职超过一年
        }
        Long orgId = oldEmployeeEntity.getOrgId();
        Long unitId = oldEmployeeEntity.getUnitId();
        Long jobLevelId = oldEmployeeEntity.getJobLevelId();
        Long jobId = oldEmployeeEntity.getJobId();
        String orgNameById = jobController.getOrgNameById(orgId);
        oldEmployeeEntity.setOrgname(orgNameById);
        String unitname = jobController.getOrgNameById(unitId);
        oldEmployeeEntity.setUnitname(unitname);
        String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
        oldEmployeeEntity.setJobLevel(jobLevelNameById);
        String jobName = jobController.getJobName(jobId);
        oldEmployeeEntity.setJobname(jobName);

        return R.ok(oldEmployeeEntity);
    }


    @PostMapping("/saveOldEmployeeArchive")
    @ApiOperation(value = "保存归档信息")
    @SysAuthorityLog(value = "保存归档信息")
    @PreAuthorize("hasAuthority('emp:gd:update')")
    public R updateOldEmployeeReinstateAndEndRemark(@RequestParam("oid") String oid, @RequestParam("endRemark") String endRemark) {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(Long.valueOf(oid));

        //删除招聘信息
        if (!StringUtils.isEmpty(employeeInfoEntity.getRecruitmentId())) {
            EmployeeRecruitmentEntity employeeRecruitmentEntity = new EmployeeRecruitmentEntity();
            employeeRecruitmentEntity.setId(employeeInfoEntity.getRecruitmentId());
            employeeRecruitmentEntity.setIsReinstate(3);
            employeeRecruitmentEntity.setIsDelete(1);
            employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
        }
        employeeInfoEntity.setIsReinstate(3);
        employeeInfoEntity.setIsDelete(1);
        employeeInfoService.updateByIdE(employeeInfoEntity);
        EmployeeArchiveEntity employeeArchiveEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeArchiveEntity.class);
        employeeArchiveEntity.setOid(null);
        employeeArchiveEntity.setIsDelete(0);
        employeeArchiveEntity.setEndRemark(endRemark);
        employeeArchiveEntity.setUpdateTime(new Date());
        //更新入职待办通知为已办理状态
        noticeController.updateNoticeTodo(Long.parseLong(oid), NoticeConst.TODO_TYPE_NEW_EMPLOYEE);
        //更新录用待办通知为已处理状态
        noticeController.updateNoticeTodo(Long.parseLong(oid), NoticeConst.TODO_TYPE_HIRE);
        return employeeArchiveService.saveE(employeeArchiveEntity);
    }


    @PostMapping("/getEmployeeArchiveServivePage")
    @ApiOperation(value = "查询归档信息")
    @PreAuthorize("hasAuthority('emp:gd:get')")
    public R<PageResult<EmployeeInfoDto>> getEmployeeArchiveServivePage(@RequestBody @Valid EmployeeListDto employeeListDto,
                                                                        HttpServletRequest request) throws Exception {
//        log.info("employeeListDto:{}",employeeListDto);

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> selectOrg = null;
        List<Long> selectUnit = null;
        List<Long> selectJob = null;
        //null未查询，size为0查询结果为空
        if (!StringUtils.isEmpty(employeeListDto.getOrgname())) {
//            selectOrg = jobDaoMssql.findOrgByName(employeeListDto.getOrgname());
            if (selectOrg == null) {
                selectOrg = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(employeeListDto.getUnitname())) {
//            selectUnit = jobDaoMssql.findOrgByName(employeeListDto.getUnitname());
            if (selectUnit == null) {
                selectUnit = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(employeeListDto.getJobname())) {
//            selectJob = jobDaoMssql.findJobIdByName(employeeListDto.getJobname());
            if (selectJob == null) {
                selectJob = new ArrayList<>();
            }
        }
        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String code = user.getString("usercode");
        //当前日期
        String date = DateUtils.format(new Date(), "yyyy-MM-dd") + " 23:59:59";
//        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.queryPage(employeeOid,name,orgname,unitname,jobname,keyword, status,isReinstate,isEntryStatus,pageNum,pageSize,orgIds);
        PageResult<EmployeeArchiveEntity> pageResult = employeeArchiveService.queryPage(employeeListDto.getEmployeeOid(), employeeListDto.getName(),
                selectOrg, selectUnit, selectJob,
                employeeListDto.getStatus(), employeeListDto.getIsReinstate(), employeeListDto.getIsEntryStatus(),
                employeeListDto.getPageNum(), employeeListDto.getPageSize(), orgIds, employeeListDto.getSocialTrainee(), date, employeeListDto.getIsOffer(), code);
        List<EmployeeArchiveEntity> list = pageResult.getList();
        ArrayList<EmployeeInfoDto> infoDtoList = new ArrayList<>();

        for (EmployeeArchiveEntity infoEntity : list) {
            Long orgId = infoEntity.getOrgId();
            Long unitId = infoEntity.getUnitId();
            Long jobId = infoEntity.getJobId();
            Long jobLevelId = infoEntity.getJobLevelId();

//            根据id去换缓存中获取组织名称
            String orgName = jobController.getOrgNameById(orgId);
            String unitName = jobController.getOrgNameById(unitId);
            //根据id去换缓存中获取岗位名称
            String jobName = jobController.getJobName(jobId);

            //根据id去换缓存中获取职级名称
            String jobLevelName = jobController.getJobLevelNameById(jobLevelId);


            EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(infoEntity, EmployeeInfoDto.class);

            employeeInfoDto.setOrgname(orgName);
            employeeInfoDto.setUnitname(unitName);
            employeeInfoDto.setJobname(jobName);
            employeeInfoDto.setJobLevel(jobLevelName);


            infoDtoList.add(employeeInfoDto);

        }
        PageResult<EmployeeInfoDto> result = new PageResult<>();
        result.setList(infoDtoList);
        result.setCurrPage(pageResult.getCurrPage());
        result.setPageSize(pageResult.getPageSize());
        result.setTotalCount(pageResult.getTotalCount());
        result.setTotalPage(pageResult.getTotalPage());

        return R.ok(result);


    }


    @GetMapping("/getEmployeeSalaryBpmById/{oid}")
    @ApiOperation(value = "根据员工id查询新员工bpm审核")
    @PreAuthorize("hasAuthority('emp:zp:get')")
    public R<EmployeeBpmDto> getEmployeeSalaryBpmById(@PathVariable("oid") Long oid) {
        EmployeeBpmEntity bpmEntity = employeeBpmService.getByIdE(oid);
        if (ObjectUtils.isEmpty(bpmEntity)) {
            return R.error("根据员工id查询为空");
        }

        EmployeeBpmDto employeeBpmDto = BeanUtilsMabach.doToDto(bpmEntity, EmployeeBpmDto.class);

//        封装参数
        setArgs(bpmEntity, employeeBpmDto);


//        getBpmImg(employeeBpmDto); //封装附件


        return R.ok(employeeBpmDto);

    }

    @PostMapping("/updateEmployeeSalaryBpmById")
    @ApiOperation(value = "修改新员工bpm审核表单")
    @SysAuthorityLog(value = "修改新员工bpm审核表单")
    @Transactional
    @PreAuthorize("hasAuthority('emp:zp:update')")
    public R updateEmployeeSalaryBpmById(@RequestBody @Valid UpdateEmployeeBpmVo updateEmployeeBpmVo, HttpServletRequest request
    ) throws Exception {
//        log.info("updateEmployeeBpmVo===========>>>>>>>>>>:{}",updateEmployeeBpmVo);
        Boolean flag = false;

        EmployeeBpmEntity employeeBpmEntity = BeanUtilsMabach.doToDto(updateEmployeeBpmVo, EmployeeBpmEntity.class);


        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(updateEmployeeBpmVo, EmployeeInfoEntity.class);
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return R.error("请先登录");
        }


        setBpmImg(updateEmployeeBpmVo); //封装附件

        String name = data.getString("name");
        String usercode = data.getString("usercode");
        employeeBpmEntity.setApplyUserCode(usercode);
        employeeBpmEntity.setApplyName(name);
        employeeInfoEntity.setPrincipalUserCode(usercode);
        employeeInfoEntity.setPrincipal(name);
        employeeBpmEntity.setUpdateTime(new Date());
        employeeInfoEntity.setUpdateTime(new Date());

        //修改招聘信息
        EmployeeInfoEntity entity = employeeInfoService.getByIdE(employeeInfoEntity.getOid());
        if (!StringUtils.isEmpty(entity.getRecruitmentId())) {
            EmployeeRecruitmentEntity employeeRecruitmentEntity = BeanUtilsMabach.doToDto(updateEmployeeBpmVo, EmployeeRecruitmentEntity.class);
            employeeRecruitmentEntity.setId(entity.getRecruitmentId());
            employeeRecruitmentEntity.setPrincipalUserCode(usercode);
            employeeRecruitmentEntity.setPrincipal(name);
            employeeRecruitmentEntity.setUpdateTime(new Date());

            employeeRecruitmentEntity.setEvaluation(CollectionUtils.isEmpty(updateEmployeeBpmVo.getEvaluation()) ? "" : ListToString((ArrayList<String>) updateEmployeeBpmVo.getEvaluation()));
            employeeRecruitmentEntity.setBackreport(CollectionUtils.isEmpty(updateEmployeeBpmVo.getBackReport()) ? "" : ListToString((ArrayList<String>) updateEmployeeBpmVo.getBackReport()));
            employeeRecruitmentEntity.setResume(CollectionUtils.isEmpty(updateEmployeeBpmVo.getResume()) ? "" : ListToString((ArrayList<String>) updateEmployeeBpmVo.getResume()));
            employeeRecruitmentEntity.setInvitationletter(CollectionUtils.isEmpty(updateEmployeeBpmVo.getInvitationLetter()) ? "" : ListToString((ArrayList<String>) updateEmployeeBpmVo.getInvitationLetter()));
            employeeRecruitmentEntity.setMeasure(CollectionUtils.isEmpty(updateEmployeeBpmVo.getMeasure()) ? "" : ListToString((ArrayList<String>) updateEmployeeBpmVo.getMeasure()));
            employeeRecruitmentEntity.setProve(CollectionUtils.isEmpty(updateEmployeeBpmVo.getProve()) ? "" : ListToString((ArrayList<String>) updateEmployeeBpmVo.getProve()));
            employeeRecruitmentEntity.setOtheratt(CollectionUtils.isEmpty(updateEmployeeBpmVo.getOtherAtt()) ? "" : ListToString((ArrayList<String>) updateEmployeeBpmVo.getOtherAtt()));

            employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
        }

        employeeInfoService.updateByIdE(employeeInfoEntity);
        EmployeeBpmEntity bpmServiceByIdE = employeeBpmService.getByIdE(updateEmployeeBpmVo.getOid());
        if (ObjectUtils.isEmpty(bpmServiceByIdE)) {
            employeeBpmService.saveE(employeeBpmEntity);
        } else {
            employeeBpmService.updateByIdE(employeeBpmEntity);
        }


        flag = true;
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }


    }

    @PostMapping("/getEmployeeRecruitmentByOid")
    @ApiOperation(value = "根据oid查询招聘信息")
    @Transactional
    public R getEmployeeRecruitmentByOid(@RequestParam String oid) {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(Long.valueOf(oid));
        EmployeeRecruitmentEntity employeeRecruitmentEntity = new EmployeeRecruitmentEntity();
        if (!StringUtils.isEmpty(employeeInfoEntity.getRecruitmentId())) {
            employeeRecruitmentEntity = employeeRecruitmentService.getByIdE(employeeInfoEntity.getRecruitmentId());
        }
        return R.ok(employeeRecruitmentEntity);
    }


    @PostMapping("/updateLast")
    @ApiOperation(value = "新员工入职代办最终确认修改")
    @SysAuthorityLog(value = "新员工入职代办最终确认修改")
    @Transactional
    @PreAuthorize("hasAuthority('emp:rzbl:update')")
    public R updateLast(@RequestBody @Valid LastEmployeeInfoUpdateVo lastEmployeeInfoUpdateVo, HttpServletRequest request) throws Exception {

        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(lastEmployeeInfoUpdateVo, EmployeeInfoEntity.class);

        EmployeeInfoUpdateVo employeeInfoUpdateVo = BeanUtilsMabach.doToDto(lastEmployeeInfoUpdateVo, EmployeeInfoUpdateVo.class);
        employeeInfoEntity.setIsHireDone(1);
//        判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,lastEmployeeInfoUpdateVo.getOid())){
//            return checkR;
//        }
//        保存亲属关系
        List<RelationEntity> relationEntityList = lastEmployeeInfoUpdateVo.getRelationEntityList();
        if (!CollectionUtils.isEmpty(relationEntityList)) {
            for (RelationEntity relationEntity : relationEntityList) {
                relationService.saveE(relationEntity);
            }
        }
        //        封装图片
        updateImg(employeeInfoUpdateVo);
        employeeInfoEntity.setIsEntryStatus(1); //确认入职

        //修改薪资状态显示
        List<SalaryChangeEntity> salaryChangeEntityList = salaryChangeDao.selectList(new QueryWrapper<SalaryChangeEntity>()
                .eq("oid", employeeInfoEntity.getOid()).eq("approve_status", 4).eq("is_delete", 0));
        if (!CollectionUtils.isEmpty(salaryChangeEntityList)) {
            SalaryChangeEntity salaryChangeEntity = salaryChangeEntityList.get(0);
            salaryChangeEntity.setApproveStatus(2);
            salaryChangeEntity.setEffectiveTime(lastEmployeeInfoUpdateVo.getHiredate());
            salaryChangeDao.updateById(salaryChangeEntity);
        }
        if (!ObjectUtils.isEmpty(lastEmployeeInfoUpdateVo.getNativeplace())) {
            employeeInfoEntity.setNativeplace(lastEmployeeInfoUpdateVo.getNativeplace().toString());
        }
//        if (!ObjectUtils.isEmpty(lastEmployeeInfoUpdateVo.getNativeplaceProvince())) {
//            employeeInfoEntity.setNativeplaceProvince(lastEmployeeInfoUpdateVo.getNativeplaceProvince().toString());
//        }

        EmployeeInfoEntity entity = employeeInfoService.getByIdE(employeeInfoEntity.getOid());
        if ("0".equals(entity.getEmployeestatus())) {
            employeeInfoEntity.setEmployeestatus("2");
        }

        R r = employeeInfoService.updateByIdE(employeeInfoEntity);

        //修改招聘数据信息
        if (!StringUtils.isEmpty(entity.getRecruitmentId())) {
            EmployeeRecruitmentEntity employeeRecruitmentEntity = new EmployeeRecruitmentEntity();
            employeeRecruitmentEntity.setId(entity.getRecruitmentId());
            employeeRecruitmentEntity.setIsHireDone(1);
            employeeRecruitmentEntity.setIsEntryStatus(1);
            employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
        }

        //薪资组分配
        SalaryDistributionEntity salaryDistributionEntity = salaryDistributionService.saveSalaryDistribution(entity, SalaryConst.SALARY_TYPE_TRY_OUT);

//        EmployeeInfoEntity employeeInfo = employeeInfoService.getByIdE(lastEmployeeInfoUpdateVo.getOid());
        //查看待入职日期是不是相同
//        if(!ObjectUtils.isEmpty(employeeInfo)&&!ObjectUtils.isEmpty(employeeInfo.getHiredate())&&!employeeInfo.getHiredate().equals(employeeInfoEntity.getHiredate())){
//            sendHireToDO(employeeInfoEntity, employeeInfo, employeeInfo.getHiredate());
//        }
        //更新入职待办通知为已办理状态
        noticeController.updateNoticeTodo(employeeInfoEntity.getOid(), NoticeConst.TODO_TYPE_NEW_EMPLOYEE);
        //新增一条入职新签合同数据
        ContractNewVo vo = new ContractNewVo();
        vo.setType(ContractConst.CONTRACT_TYPE_NEW);
        vo.setOperateType(ContractConst.CONTRACT_OPERATE_ENTRY);
        vo.setOid(entity.getOid());
        vo.setRelateId(entity.getOid());
        contractController.saveNewContract(vo);
        String salaryContent = "您有一位待分配薪资和发薪单位员工：" + employeeInfoEntity.getName();
        String contractContent = "您有一位入职待新签劳动合同员工：" + employeeInfoEntity.getName();
        qwMsg.sendNoticeMsg("薪资分配", salaryContent, NoticeConst.TODO_TYPE_SALARY_ALLOT, false, employeeInfoEntity.getOid(), salaryDistributionEntity.getId(), "薪资分配", null, new Date(), employeeInfoEntity.getOrgId());
        qwMsg.sendNoticeMsg("合同发送", contractContent, NoticeConst.TODO_TYPE_CONTRACT_SEND, false, employeeInfoEntity.getOid(), employeeInfoEntity.getOid(), "合同", null, new Date(), employeeInfoEntity.getOrgId());


        //新增账号管理 台账信息
        EmployeeChangeEntity employeeChangeEntity = new EmployeeChangeEntity();
        employeeChangeEntity.setCreateTime(new Date());
        employeeChangeEntity.setIsDelete(0);
        employeeChangeEntity.setName(employeeInfoEntity.getName());
        employeeChangeEntity.setJobName(jobController.getJobName(employeeInfoEntity.getJobId()));
        employeeChangeEntity.setMobile(employeeInfoEntity.getMobile());
        employeeChangeEntity.setOid(employeeInfoEntity.getOid());
        employeeChangeEntity.setOrgName(jobController.getOrgNameById(employeeInfoEntity.getOrgId()));
        employeeChangeEntity.setUnitName(jobController.getOrgNameById(employeeInfoEntity.getUnitId()));
        employeeChangeEntity.setUnitId(employeeInfoEntity.getUnitId());
        // 3新员工入职，4复职员工入职
        if (0 == entity.getIsReinstate()) {
            employeeChangeEntity.setType(EmployeeChangeConst.CHANGE_TYPE_NEW_TRANSFER);
        } else {
            employeeChangeEntity.setType(EmployeeChangeConst.CHANGE_TYPE_REINSTATEMENT_TRANSFER);
        }
        employeeChangeController.addEmployeeChangeInfo(employeeChangeEntity);

//        删除员工存在redis中的token
        String token = entity.getToken();
        if (!StringUtils.isEmpty(token)) {
            redisTemplate.delete(token);
        }

//        neusoftEmployeeChangeService.uploadEmployeeChange(entity);
        /**
         * 用队列处理业务，获取ehr的工号并写入到本地库里
         */
//         Long oid = lastEmployeeInfoUpdateVo.getOid();
//        String code = entity.getCode();
////        如果没有工号，才分配工号
//        if (StringUtils.isEmpty(code)){
//            messageSender.send(GetUserCodeMqConfig.SMS_EXCHANGE,GetUserCodeMqConfig.SMS_ROUTING_KEY,oid+"");
//        }


        neusoftEmployeeChangeService.uploadEmployeeChange(entity);
        return r;


    }

    public void sendHireToDo(EmployeeInfoEntity employeeInfo) {
//        String dString = DateUtils.format(employeeInfo.getHiredate(), "yyyy-MM-dd");
//        String nowString = DateUtils.format(new Date(), "yyyy-MM-dd");
//        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dString);
//        Date now = new SimpleDateFormat("yyyy-MM-dd").parse(nowString);
        //修改入职时间发送待入职信息
        String content = "您有一条入职流程需要处理：" + employeeInfo.getName();
        //发送企微信息以及入职待办通知
        qwMsg.sendNoticeMsg("入职待办", content, TodoConst.PRE_ENTRY, false, employeeInfo.getOid(), employeeInfo.getOid(), "入职", null, employeeInfo.getHiredate(), employeeInfo.getOrgId());
    }


    /**
     * 发送录用待办
     *
     * @param employeeInfoEntity
     */
    private void sendNewEmployeeToDo(EmployeeInfoEntity employeeInfoEntity, String userCode) {
        String content = "您有一条录用流程需要处理：" + employeeInfoEntity.getName();
        qwMsg.sendNoticeMsg("录用待办", content, TodoConst.PRE_HIRE, false, employeeInfoEntity.getOid(), employeeInfoEntity.getOid(), "录用", userCode, new Date(), null);
    }


    @GetMapping("/deleteMainInfo/{id}")
    @ApiOperation(value = "删除新员工主体信息")
    @SysAuthorityLog(value = "删除新员工主体信息")
    @PreAuthorize("hasAuthority('emp:zpsc:delete')")
    @Transactional
    public R deleteMainInfo(@PathVariable("id") Long id, HttpServletRequest request) throws Exception {
        Boolean flag = false;
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,employeeInfoEntity.getOid())){
//            return checkR;
//        }
        R r1 = employeeBpmService.removeOneById(id);
        R r = employeeInfoService.removeOneById(id);
        flag = true;
        if (flag) {
            return R.ok();
        }
        return R.error();
    }


    @GetMapping("/getEduByOid/{id}")
    @ApiOperation(value = "根据员工id查询教育信息")
    public R getEduByOid(@PathVariable("id") Long id) {

        List<EmployeeEducationEntity> employeeEducationListByOid = employeeEducationService.findEmployeeEducationListByOid(id);

        return R.ok(employeeEducationListByOid);
    }


    @GetMapping("/getRelativeRecords/{oid}")
    @ApiOperation(value = "根据oid获取员工亲属报备信息")
    public R<List<RelativeRecordsEntity>> getRelativeRecords(@PathVariable("oid") Long oid, HttpServletRequest request) throws Exception {

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("员工信息不存在");
        }
        List<RelativeRecordsEntity> relativeRecordsEntities = relativeRecordsDao.selectList(new QueryWrapper<RelativeRecordsEntity>().eq("oid", oid).eq("is_delete", 0));


        return R.ok(relativeRecordsEntities);
    }


    @PostMapping("/saveRelativeRecords")
    @ApiOperation(value = "添加员工亲属报备信息")
    @SysAuthorityLog(value = "添加员工亲属报备信息")
    public R saveRelativeRecords(@RequestBody @Valid RelativeRecordsEntity relativeRecordsEntity, HttpServletRequest request) throws Exception {

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(relativeRecordsEntity.getOid());
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("员工信息不存在");
        }
        Long id = snowflakeIdWorker.nextId();
        relativeRecordsEntity.setId(id);
        R r = relativeRecordsService.saveE(relativeRecordsEntity);

//        ////neuEmployeeBaseInfoService.saveRelative(relativeRecordsEntity.getId());
        return r;
    }

    @PostMapping("/updateRelativeRecords")
    @ApiOperation(value = "修改员工亲属报备信息")
    @SysAuthorityLog(value = "添加员工亲属报备信息")
    public R updateRelativeRecords(@RequestBody @Valid RelativeRecordsEntity relativeRecordsEntity, HttpServletRequest request) throws Exception {

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(relativeRecordsEntity.getOid());
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("员工信息不存在");
        }

        R r = relativeRecordsService.updateByIdE(relativeRecordsEntity);
//        ////neuEmployeeBaseInfoService.saveRelative(relativeRecordsEntity.getId());
        return r;
    }

    @DeleteMapping("/deleteRelativeRecords/{id}")
    @ApiOperation(value = "删除员工亲属报备信息")
    @SysAuthorityLog(value = "添加员工亲属报备信息")
    public R deleteRelativeRecords(@PathVariable("id") Long id) throws Exception {

//        ////neuEmployeeBaseInfoService.deleteOtherInfo(id, EmployeeInfoConst.EMPLOYEE_DEL_NHQS);
        R r = relativeRecordsService.removeOneById(id);

        return r;
    }


    @GetMapping("/getInternalAward/{oid}")
    @ApiOperation(value = "根据oid获取员工内部奖惩信息")
    public R<List<InternalAwardEntity>> getInternalAward(@PathVariable("oid") Long oid, HttpServletRequest request) throws Exception {

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("员工信息不存在");
        }
        List<InternalAwardEntity> internalAwardEntityList = internalAwardDao.selectList(new QueryWrapper<InternalAwardEntity>().eq("oid", oid).eq("is_delete", 0));
        return R.ok(internalAwardEntityList);
    }


    @PostMapping("/saveInternalAward")
    @ApiOperation(value = "添加员工内部奖惩信息")
    @SysAuthorityLog(value = "添加员工内部奖惩信息")
    public R saveInternalAward(@RequestBody @Valid InternalAwardEntity internalAwardEntity, HttpServletRequest request) throws Exception {

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(internalAwardEntity.getOid());
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("员工信息不存在");
        }
        Long id = snowflakeIdWorker.nextId();
        internalAwardEntity.setId(id);
        R r = internalAwardService.saveE(internalAwardEntity);

//        ////neuEmployeeBaseInfoService.saveInternalAward(internalAwardEntity.getId());
        return r;
    }

    @PostMapping("/updateInternalAward")
    @ApiOperation(value = "修改员工内部奖惩信息")
    @SysAuthorityLog(value = "添加员工内部奖惩信息")
    public R updateInternalAward(@RequestBody @Valid InternalAwardEntity internalAwardEntity, HttpServletRequest request) throws Exception {

        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(internalAwardEntity.getOid());
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("员工信息不存在");
        }

        R r = internalAwardService.updateByIdE(internalAwardEntity);
//        ////neuEmployeeBaseInfoService.saveInternalAward(internalAwardEntity.getId());
        return r;
    }

    @DeleteMapping("/deleteInternalAward/{id}")
    @ApiOperation(value = "删除员工内部奖惩信息")
    @SysAuthorityLog(value = "添加员工内部奖惩信息")
    public R deleteInternalAward(@PathVariable("id") Long id) throws Exception {

//        ////neuEmployeeBaseInfoService.deleteOtherInfo(id, EmployeeInfoConst.EMPLOYEE_DEL_BUJC);
        internalAwardDao.deleteById(id);
        return R.ok();
    }


    @PostMapping("/saveEducationInfo")
    @ApiOperation(value = "添加新员工教育信息")
    @SysAuthorityLog(value = "添加新员工教育信息")
    public R saveEducationInfo(@RequestBody @Valid EmployeeEducationVo employeeEducationVo, HttpServletRequest request) throws Exception {
        EmployeeEducationEntity employeeEducationEntity = BeanUtilsMabach.doToDto(employeeEducationVo, EmployeeEducationEntity.class);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(employeeEducationEntity.getEmpoid());
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("员工信息不存在");
        }
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,employeeEducationEntity.getEmpoid())){
//            return checkR;
//        }
        employeeEducationEntity.setOperatetime(new Date());
        Long id = snowflakeIdWorker.nextId();
        employeeEducationEntity.setOid(id);
        R r = employeeEducationService.saveE(employeeEducationEntity);

//        ////neuEmployeeBaseInfoService.saveEducation(employeeEducationEntity.getOid());
        return r;
    }

    @PostMapping("/updateEducationInfo")
    @ApiOperation(value = "修改员工教育信息")
    @SysAuthorityLog(value = "修改员工教育信息")
    public R updateEducationInfo(@RequestBody @Valid EmployeeEducationUpdateVo employeeEducationVo, HttpServletRequest request) throws Exception {
        EmployeeEducationEntity employeeEducationEntity = BeanUtilsMabach.doToDto(employeeEducationVo, EmployeeEducationEntity.class);

//        EmployeeInfoEntity employeeBpmEntity = employeeInfoService.getByIdE(employeeEducationEntity.getEmpoid());
        if (ObjectUtils.isEmpty(employeeEducationEntity)) {
            return R.error("员工信息不存在");
        }
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeBpmEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,employeeEducationEntity.getEmpoid())){
//            return checkR;
//        }
        employeeEducationEntity.setOperatetime(new Date());
        R r = employeeEducationService.updateByIdE(employeeEducationEntity);

//        ////neuEmployeeBaseInfoService.saveEducation(employeeEducationEntity.getOid());
        return r;
    }

    @GetMapping("/deleteEducation/{id}")
    @ApiOperation(value = "删除员工教育信息")
    @SysAuthorityLog(value = "删除员工教育信息")
    public R deleteEducation(@PathVariable("id") Long id, HttpServletRequest request) throws Exception {
        EmployeeEducationEntity entity = employeeEducationService.getByIdE(id);
        if (ObjectUtils.isEmpty(entity)) {
            return R.error("员工信息不存在！");
        }
//        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(entity.getEmpoid());
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getOrgId(),true);
//        if(!R.isOk.equals(checkR.getStatus())&&!isPrincipalUser(request,entity.getEmpoid())){
//            return checkR;
//        }
//        ////neuEmployeeBaseInfoService.deleteOtherInfo(id, EmployeeInfoConst.EMPLOYEE_DEL_EDUCATION);
        R r = employeeEducationService.removeOneById(id);

        return r;
    }

    @GetMapping("/getInorgInfo/{id}")
    @ApiOperation(value = "获取员工id政治面貌")
    public R<List<EmployeeInorgnameEntity>> getInorgInfo(@PathVariable("id") Long id) {
        List<EmployeeInorgnameEntity> byEmpId = employeeInorgnameService.getByEmpId(id);
        return R.ok(byEmpId);
    }


    @PostMapping("/saveInorgInfo")
    @ApiOperation(value = "添加新政治面貌信息")
    @SysAuthorityLog(value = "添加新政治面貌信息")
    public R saveInorg(@RequestBody @Valid EmployeeInorgnameVo employeeInorgnameVo) {
        EmployeeInorgnameEntity employeeInorgnameEntity = BeanUtilsMabach.doToDto(employeeInorgnameVo, EmployeeInorgnameEntity.class);
        employeeInorgnameEntity.setOperatetime(new Date());
        Long id = snowflakeIdWorker.nextId();
        employeeInorgnameEntity.setId(id);
        R r = employeeInorgnameService.saveE(employeeInorgnameEntity);
//        log.info("入党：{}",employeeInorgnameVo);
//        ////neuEmployeeBaseInfoService.saveGroup(id);
        return r;
    }

    @PostMapping("/updateInorgInfo")
    @ApiOperation(value = "修改新员工政治面貌信息")
    @SysAuthorityLog(value = "修改新员工政治面貌信息")
    public R updateInorg(@RequestBody @Valid EmployeeInorgnameUpdateVo employeeInorgnameUpdateVo) {
        EmployeeInorgnameEntity employeeInorgnameEntity = BeanUtilsMabach.doToDto(employeeInorgnameUpdateVo, EmployeeInorgnameEntity.class);
        employeeInorgnameEntity.setOperatetime(new Date());
        R r = employeeInorgnameService.updateByIdE(employeeInorgnameEntity);

        ////neuEmployeeBaseInfoService.saveGroup(employeeInorgnameEntity.getId());
        return r;
    }

    @GetMapping("/deleteInorg/{id}")
    @ApiOperation(value = "删除员工政治面貌信息")
    @SysAuthorityLog(value = "删除员工政治面貌信息")
    public R deleteInorg(@PathVariable("id") String id) {
        ////neuEmployeeBaseInfoService.deleteOtherInfo(Long.valueOf(id), EmployeeInfoConst.EMPLOYEE_DEL_XZDP);
        R r = employeeInorgnameService.removeOneById(Long.valueOf(id));

        return r;
    }


    @GetMapping("/getSocietyInfo/{id}")
    @ApiOperation(value = "根据员工id查询工作履历")
    public R<List<EmployessSocietyexperienceEntity>> getSocietyInfo(@PathVariable("id") Long id) {


        List<EmployessSocietyexperienceEntity> byEmpId = employessSocietyexperienceService.getByEmpId(id);
        return R.ok(byEmpId);
    }

    @PostMapping("/saveSociety")
    @ApiOperation(value = "添加新员工作履历")
    @SysAuthorityLog(value = "添加新员工作履历")
    public R saveSociety(@RequestBody @Valid EmployessSocietyVo employessSocietyVo) {
        Long empoid = employessSocietyVo.getEmpoid();
        EmployeeInfoEntity byIdE = employeeInfoService.getByIdE(empoid);
        if (ObjectUtils.isEmpty(byIdE)) {
            return R.error("查不到该员工主体信息");
        }
        EmployessSocietyexperienceEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, EmployessSocietyexperienceEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        Long id = snowflakeIdWorker.nextId();
        employessSocietyexperienceEntity.setOid(id);
        R r = employessSocietyexperienceService.saveE(employessSocietyexperienceEntity);
        ////neuEmployeeBaseInfoService.saveSociety(employessSocietyexperienceEntity.getOid());
        log.info("工作信息参数是：{}", employessSocietyVo);
        return r;
    }

    @PostMapping("/updateSociety")
    @ApiOperation(value = "修改新员工作履历")
    @SysAuthorityLog(value = "修改新员工作履历")
    public R updateSociety(@RequestBody @Valid EmployessSocietyUpdateVo employessSocietyVo) {

        EmployessSocietyexperienceEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, EmployessSocietyexperienceEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        R r = employessSocietyexperienceService.updateByIdE(employessSocietyexperienceEntity);

        ////neuEmployeeBaseInfoService.saveSociety(employessSocietyexperienceEntity.getOid());
        return r;
    }

    @GetMapping("/deleteSociety/{id}")
    @ApiOperation(value = "删除员工工作履历")
    @SysAuthorityLog(value = "删除员工工作履历")
    public R deleteSociety(@PathVariable("id") Long id) {
        ////neuEmployeeBaseInfoService.deleteOtherInfo(id, EmployeeInfoConst.EMPLOYEE_DEL_WORK);
        R r = employessSocietyexperienceService.removeOneById(id);

        return r;
    }


    @GetMapping("/getFamilyListByOid/{id}")
    @ApiOperation(value = "获取员工家庭信息")
    public R<List<FamilyMemberEntity>> getFamilyListByOid(@PathVariable("id") Long id) {
        List<FamilyMemberEntity> familyMemberEntities = familyMemberService.getListByEmpId(id);
        return R.ok(familyMemberEntities);
    }

    @PostMapping("/saveFamily")
    @ApiOperation(value = "添加新员工家庭联关系")
    @SysAuthorityLog(value = "添加新员工家庭联关系")
    public R saveFamily(@RequestBody @Valid FamilyMemberVo employessSocietyVo) {
        FamilyMemberEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, FamilyMemberEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        Long id = snowflakeIdWorker.nextId();
        employessSocietyexperienceEntity.setOid(id);
        R r = familyMemberService.saveE(employessSocietyexperienceEntity);
        //neuEmployeeBaseInfoService.saveFamily(employessSocietyexperienceEntity.getOid());
        return r;
    }

    @PostMapping("/updateFamily")
    @ApiOperation(value = "修改员工家庭联关系")
    @SysAuthorityLog(value = "修改员工家庭联关系")
    public R updateFamily(@RequestBody @Valid FamilyMemberUpdateVo employessSocietyVo) {
//        log.info("参数为:{}",employessSocietyVo);
        FamilyMemberEntity employessSocietyexperienceEntity = BeanUtilsMabach.doToDto(employessSocietyVo, FamilyMemberEntity.class);
        employessSocietyexperienceEntity.setOperatetime(new Date());
        R r = familyMemberService.updateByIdE(employessSocietyexperienceEntity);

        //neuEmployeeBaseInfoService.saveFamily(employessSocietyexperienceEntity.getOid());
        return r;
    }

    @GetMapping("/deleteFamily/{id}")
    @ApiOperation(value = "删除员工家庭成员信息")
    @SysAuthorityLog(value = "删除员工家庭成员信息")
    public R deleteFamily(@PathVariable("id") Long id) {
        //neuEmployeeBaseInfoService.deleteOtherInfo(id, EmployeeInfoConst.EMPLOYEE_DEL_FAMLY);
        R r = familyMemberService.removeOneById(id);

        return r;
    }

    @GetMapping("/getProfessionstyle")
    @ApiOperation(value = "获取专业类型")
    public R getProfessionstyle() {
//        jobDaoMssql.findProfessionstyle("CODE_professionstyle");
        List<professionstyleDto> professionstyleDtoList = new ArrayList<>();

        List<Map<String, Object>> mapList = finOrgByPid(professionstyleDtoList, "-1");
        return R.ok(mapList);
    }


    @GetMapping("/updateEmployeeInfoCodeByOid")
    @ApiOperation(value = "根据oid修改员工工号")
    @SysAuthorityLog(value = "根据oid修改员工工号")
    public R updateEmployeeInfo(@RequestParam("oid") String oid, @RequestParam("code") String code) {
        List<EmployeeInfoEntity> employeeInfoEntityList = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code", code).eq("is_delete", 0));
        if (!CollectionUtils.isEmpty(employeeInfoEntityList)) {
            R.error("该工号已使用，请重新填写");
        }
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid", oid).eq("is_delete", 0));
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            R.error("未找到该员工");
        }
        employeeInfoEntity.setCode(code);
        employeeInfoDao.updateById(employeeInfoEntity);
        return R.ok();
    }

   /* @GetMapping("/getEmployeeInfoPage")
    public R getEmployeeInfoPage(@RequestParam(value = "name", required = false) String name,
                                 @RequestParam(value = "orgname", required = false) String orgname,
                                 @RequestParam(value = "unitname", required = false) String unitname,
                                 @RequestParam(value = "jobname", required = false) String jobname,
                                 @RequestParam(value = "code", required = false) String code,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) throws Exception {
        List<>employeeBpmService.selectAllEmployeeIngo( name, orgname,unitname,jobname,code,pageNum,pageSize);




        return null;
    }*/


   /* @GetMapping("/getEmployeeInfoPage")
    @ApiOperation(value = "分页查询员工信息")
    public R getEmployeeInfoPage(@RequestParam(value = "name", required = false) String name,
                                 @RequestParam(value = "orgname", required = false) String orgname,
                                 @RequestParam(value = "unitname", required = false) String unitname,
                                 @RequestParam(value = "jobname", required = false) String jobname,
                                 @RequestParam(value = "code", required = false) String code,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) throws Exception {


        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        List<Long> selectOrg = null;
        List<Long> selectUnit = null;
        List<Long> selectJob = null;
        //null未查询，size为0查询结果为空
        if (!StringUtils.isEmpty(orgname)) {
//            selectOrg = jobDaoMssql.findOrgByName(orgname);
            if (selectOrg == null) {
                selectOrg = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(unitname)) {
//            selectUnit = jobDaoMssql.findOrgByName(unitname);
            if (selectUnit == null) {
                selectUnit = new ArrayList<>();
            }
        }
        if (!StringUtils.isEmpty(jobname)) {
//            selectJob = jobDaoMssql.findJobIdByName(jobname);
            if (selectJob == null) {
                selectJob = new ArrayList<>();
            }
        }*/

/*
        PageResult result = employeeInfoService.queryEmployeePage(name, orgIds, code, selectOrg, selectUnit, selectJob, pageNum, pageSize);
        List<EmployeeInfoEntity> employeeInfoEntityList = result.getList();
        for (EmployeeInfoEntity employeeInfoEntity : employeeInfoEntityList) {
            if (employeeInfoEntity.getJobId() != null)
                employeeInfoEntity.setJobname(jobController.getJobName(employeeInfoEntity.getJobId()));
            if (employeeInfoEntity.getOrgId() != null)
                employeeInfoEntity.setOrgname(jobController.getOrgNameById(employeeInfoEntity.getOrgId()));
            if (employeeInfoEntity.getUnitId() != null)
                employeeInfoEntity.setUnitname(jobController.getOrgNameById(employeeInfoEntity.getUnitId()));
        }
        result.setList(employeeInfoEntityList);
        return R.ok(result);
    }*/


    private void setImg(@RequestBody EmployeeInfoVo employeeInfoVo, Long id) {
        //        上传原单位薪资流水
        List<String> oldSalaryRecordUrl = employeeInfoVo.getOldSalaryRecordUrl();
        if (!CollectionUtils.isEmpty(oldSalaryRecordUrl)) {
            for (String s : oldSalaryRecordUrl) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setName("原公司工资流水");
                imgUrlEntity.setOid(id);
                imgUrlEntity.setType(1); //0:流水，1：头像
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(s);
                imgUrlService.saveE(imgUrlEntity);
            }
        }
//        毕业证
        String graduationUrl = employeeInfoVo.getGraduationUrl();
        if (!StringUtils.isEmpty(graduationUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(2); //0:流水，1：头像，2：毕业证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("毕业证");
            imgUrlEntity.setUrl(graduationUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        学位证
        String degreeUrl = employeeInfoVo.getDegreeUrl();
        if (!StringUtils.isEmpty(degreeUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(3); //0:流水，1：头像，2：毕业证,3:学位证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("学位证");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        离职证明
        String dimissionUrl = employeeInfoVo.getDimissionUrl();
        if (!StringUtils.isEmpty(dimissionUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(4); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("离职证明");
            imgUrlEntity.setUrl(dimissionUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        离职报告
        String healthUrl = employeeInfoVo.getHealthUrl();
        if (!StringUtils.isEmpty(healthUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(5); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("体检报告");
            imgUrlEntity.setUrl(healthUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

        String photoUrl = employeeInfoVo.getPhotoUrl();
        if (!StringUtils.isEmpty(photoUrl)) {

            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(0); //0:流水，1：头像
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("1寸照片");
            imgUrlEntity.setUrl(photoUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

        List<String> idcardImgs = employeeInfoVo.getIdcardImgs();
        if (!CollectionUtils.isEmpty(idcardImgs)) {
            for (String idcardImg : idcardImgs) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(6); //0:流水，1：头像
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("身份证正反面");
                imgUrlEntity.setUrl(idcardImg);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> credential = employeeInfoVo.getCredential(); //证书
        if (!CollectionUtils.isEmpty(credential)) {
            for (String s : credential) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(10); //0:流水，1：头像
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("职称证书");
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> attachments = employeeInfoVo.getAttachments();
        if (!CollectionUtils.isEmpty(attachments)) {
            for (String attachment : attachments) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(11); //0:流水，1：头像
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("其他附件");
                imgUrlEntity.setUrl(attachment);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }

    }


    private void getBpmImg(EmployeeBpmDto employeeBpmDto) {
        Long oid = employeeBpmDto.getOid();
        //        面试评价表
        List<ImgUrlEntity> evaluation = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 13));
        employeeBpmDto.setEvaluation(evaluation);
//背调报告
        List<ImgUrlEntity> backReport = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 14));
        employeeBpmDto.setBackReport(backReport);
//        简历原件
        List<ImgUrlEntity> resume = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 15));
        employeeBpmDto.setResume(resume);
//录用邀约函
        List<ImgUrlEntity> invitationLetter = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 16));
        employeeBpmDto.setInvitationLetter(invitationLetter);

        //岗位薪资测算表
        List<ImgUrlEntity> measure = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 17));
        employeeBpmDto.setMeasure(measure);

        //银行流水/薪资证明
        List<ImgUrlEntity> prove = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 18));
        employeeBpmDto.setProve(prove);

        //其他附件
        List<ImgUrlEntity> otherAtt = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 19));
        employeeBpmDto.setOtherAtt(otherAtt);
    }


    private void setBpmImg(@RequestBody @Valid UpdateEmployeeBpmVo updateEmployeeBpmVo) {
        Long oid = updateEmployeeBpmVo.getOid();
//        面试评价表
        List<String> evaluation = updateEmployeeBpmVo.getEvaluation();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 13));
        if (!CollectionUtils.isEmpty(evaluation)) {
            for (String s : evaluation) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(13);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        背调报告
        List<String> backReport = updateEmployeeBpmVo.getBackReport();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 14));
        if (!CollectionUtils.isEmpty(backReport)) {
            for (String s : backReport) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(14);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//简历原件
        List<String> resume = updateEmployeeBpmVo.getResume();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 15));
        if (!CollectionUtils.isEmpty(resume)) {
            for (String s : resume) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(15);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        录用邀约函
        List<String> invitationLetter = updateEmployeeBpmVo.getInvitationLetter();

        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 16));
        if (!CollectionUtils.isEmpty(invitationLetter)) {
            for (String s : invitationLetter) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(16);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }

//        岗位薪资测算表
        List<String> measure = updateEmployeeBpmVo.getMeasure();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 17));
        if (!CollectionUtils.isEmpty(measure)) {
            for (String s : measure) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(17);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        银行流水/薪资证明
        List<String> prove = updateEmployeeBpmVo.getProve();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 18));
        if (!CollectionUtils.isEmpty(prove)) {
            for (String s : prove) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(18);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
//        其他附件
        List<String> otherAtt = updateEmployeeBpmVo.getOtherAtt();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 19));
        if (!CollectionUtils.isEmpty(otherAtt)) {
            for (String s : otherAtt) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(19);
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlDao.insert(imgUrlEntity);
            }
        }
    }


    @Transactional
    public void updateImg(@RequestBody EmployeeInfoUpdateVo employeeInfoUpdateVo) {
        Long oid = employeeInfoUpdateVo.getOid();
        //        上传原单位薪资流水
        List<String> oldSalaryRecordUrl = employeeInfoUpdateVo.getOldSalaryRecordUrl();
//        先删除
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 1));
        if (!CollectionUtils.isEmpty(oldSalaryRecordUrl)) {
            for (String s : oldSalaryRecordUrl) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setName("原公司工资流水");
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(1); //0:流水，1：头像
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(s);
                imgUrlService.saveE(imgUrlEntity);
            }
        }
//        毕业证
        String graduationUrl = employeeInfoUpdateVo.getGraduationUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 2)); //先删除
        if (!StringUtils.isEmpty(graduationUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(2); //0:流水，1：头像，2：毕业证
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("毕业证");
            imgUrlEntity.setUrl(graduationUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        学位证
        String degreeUrl = employeeInfoUpdateVo.getDegreeUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 3)); //先删除
        if (!StringUtils.isEmpty(degreeUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(3); //0:流水，1：头像，2：毕业证,3:学位证
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("学位证");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        离职证明
        String dimissionUrl = employeeInfoUpdateVo.getDimissionUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 4)); //先删除
        if (!StringUtils.isEmpty(dimissionUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(4); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("离职证明");
            imgUrlEntity.setUrl(dimissionUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        体检报告
        String healthUrl = employeeInfoUpdateVo.getHealthUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 5)); //先删除
        if (!StringUtils.isEmpty(healthUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(5); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("体检报告");
            imgUrlEntity.setUrl(healthUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        头像
        String photoUrl = employeeInfoUpdateVo.getPhotoUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 0)); //先删除
        if (!StringUtils.isEmpty(photoUrl)) {

            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(0); //0:流水，1：头像
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setName("1寸照片");
            imgUrlEntity.setUrl(photoUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }


        List<String> idcardImgs = employeeInfoUpdateVo.getIdcardImgs();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 6)); //先删除
        if (!CollectionUtils.isEmpty(idcardImgs)) {
            for (String idcardImg : idcardImgs) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(6); //0:流水，1：头像
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setName("身份证正反面");
                imgUrlEntity.setUrl(idcardImg);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> credential = employeeInfoUpdateVo.getCredential(); //证书
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 10)); //先删除
        if (!CollectionUtils.isEmpty(credential)) {
            for (String s : credential) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(10); //0:流水，1：头像
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setName("职称证书");
                imgUrlEntity.setUrl(s);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
        List<String> attachments = employeeInfoUpdateVo.getAttachments();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 11)); //先删除
        if (!CollectionUtils.isEmpty(attachments)) {
            for (String attachment : attachments) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(11); //11:其他附件
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setName("其他附件");
                imgUrlEntity.setUrl(attachment);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }
        }
    }


    /**
     * 根据身份证查询旧员工
     *
     * @param idCard
     * @return
     */

    public OldEmployeeEntity findEmpByIdcard(String idCard) {

//        jobDaoMssql.findEmpByIdcard(idCard);
        List<OldEmployeeBo> empByIdcards = new ArrayList<>();
        if (CollectionUtils.isEmpty(empByIdcards)) {
            return null;
        }
        OldEmployeeBo empByIdcard = empByIdcards.get(0);
        OldEmployeeEntity oldEmployeeEntity = BeanUtilsMabach.doToDto(empByIdcard, OldEmployeeEntity.class);
        Long professionJoblevelId = empByIdcard.getProfessionJoblevelId();
        Long managementJoblevelId = empByIdcard.getManagementJoblevelId();
        if (managementJoblevelId != null) {
            oldEmployeeEntity.setJobLevelType(2);
            oldEmployeeEntity.setJobLevelId(managementJoblevelId);
        } else {
            oldEmployeeEntity.setJobLevelType(1);
            oldEmployeeEntity.setJobLevelId(professionJoblevelId);
        }


        Date dimissiondate = empByIdcard.getDimissiondate();


        Integer days = null;
        if (dimissiondate != null) {
            days = DateUtils.daysBetween(dimissiondate, new Date());
        }


        oldEmployeeEntity.setDaysBetween(days);
        oldEmployeeEntity.setOldhiredate(oldEmployeeEntity.getHiredate());


        return oldEmployeeEntity;

    }


    private void getImg(Long oid, EmployeeInfoDto employeeInfoDto) {
        //        如果薪资流水不为空，则封装进去
        List<ImgUrlEntity> imgUrlEntities = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 1));
        if (!CollectionUtils.isEmpty(imgUrlEntities)) {
            ArrayList<String> recordUrls = new ArrayList<>();
            for (ImgUrlEntity imgUrlEntity : imgUrlEntities) {
                recordUrls.add(imgUrlEntity.getUrl());
            }
            employeeInfoDto.setOldSalaryRecordUrl(recordUrls);
        }
//        封装头像
        ImgUrlEntity imgUrlEntity = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 0));
        if (!ObjectUtils.isEmpty(imgUrlEntity)) {
            employeeInfoDto.setPhotoUrl(imgUrlEntity.getUrl());
        }

        //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
        ImgUrlEntity imgUrlEntity2 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 2));
        if (!ObjectUtils.isEmpty(imgUrlEntity2)) {
            employeeInfoDto.setGraduationUrl(imgUrlEntity2.getUrl());
        }
//        学位证
        ImgUrlEntity imgUrlEntity3 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 3));
        if (!ObjectUtils.isEmpty(imgUrlEntity3)) {
            employeeInfoDto.setDegreeUrl(imgUrlEntity3.getUrl());
        }
//        离职证明
        ImgUrlEntity imgUrlEntity4 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 4));
        if (!ObjectUtils.isEmpty(imgUrlEntity4)) {
            employeeInfoDto.setDimissionUrl(imgUrlEntity4.getUrl());
        }
//        体检报告
        ImgUrlEntity imgUrlEntity5 = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 5));
        if (!ObjectUtils.isEmpty(imgUrlEntity5)) {
            employeeInfoDto.setHealthUrl(imgUrlEntity5.getUrl());
        }

        //        身份证
        List<ImgUrlEntity> imgUrlEntityList = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 6));
        ArrayList<String> strings = new ArrayList<>();
        if (!CollectionUtils.isEmpty(imgUrlEntityList)) {
            for (ImgUrlEntity urlEntity : imgUrlEntityList) {
                strings.add(urlEntity.getUrl());
            }
            employeeInfoDto.setIdcardImgs(strings);
        }

//职称
        List<ImgUrlEntity> imgUrlEntityList3 = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 10));
        ArrayList<String> strings1 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(imgUrlEntityList3)) {
            for (ImgUrlEntity urlEntity : imgUrlEntityList3) {
                strings1.add(urlEntity.getUrl());
            }
            employeeInfoDto.setCredential(strings1);
        }

//        其他附件

        List<ImgUrlEntity> imgUrlEntityList4 = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", oid).eq("type", 11));
        ArrayList<String> strings2 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(imgUrlEntityList4)) {
            for (ImgUrlEntity urlEntity : imgUrlEntityList4) {
                strings2.add(urlEntity.getUrl());
            }
            employeeInfoDto.setAttachments(strings2);
        }

    }


    public String getUserCode() {
        Date date = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = format.format(date);
        String nm = new SimpleDateFormat("yyyyMMdd").format(date);
        Long max = employeeInfoDao.getEmployeeOidList(datestr) + 1;
        String employeeOidStr = String.format("%05d", max);
        return nm + employeeOidStr;
    }

    /**
     * 保存图片
     *
     * @param memberEmpBpmUpdateVo
     * @return
     */
    private void saveImg(@RequestBody @Valid MemberEmpBpmUpdateVo memberEmpBpmUpdateVo) {
        Long id = memberEmpBpmUpdateVo.getOid();
//修改流水
        List<String> oldSalaryRecordUrl = memberEmpBpmUpdateVo.getOldSalaryRecordUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 1));
        if (!CollectionUtils.isEmpty(oldSalaryRecordUrl)) {

            for (String s : oldSalaryRecordUrl) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setName("原公司工资流水");
                imgUrlEntity.setOid(id);
                imgUrlEntity.setType(1);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(s);
                imgUrlService.saveE(imgUrlEntity);

            }
        }
//        照片
        String photoUrl = memberEmpBpmUpdateVo.getPhotoUrl();
        if (!StringUtils.isEmpty(photoUrl)) {

            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 0));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(0);
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("1寸照片");
            imgUrlEntity.setUrl(photoUrl);
            imgUrlEntity.setCreateTime(new Date());

            imgUrlService.saveE(imgUrlEntity);
        }

        //        毕业证
        String graduationUrl = memberEmpBpmUpdateVo.getGraduationUrl();
        if (!StringUtils.isEmpty(graduationUrl)) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 2));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(2); //0:流水，1：头像，2：毕业证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("毕业证");
            imgUrlEntity.setUrl(graduationUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        学位证
        String degreeUrl = memberEmpBpmUpdateVo.getDegreeUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 3));
        if (!StringUtils.isEmpty(degreeUrl)) {

            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(3); //0:流水，1：头像，2：毕业证,3:学位证
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("学位证");
            imgUrlEntity.setUrl(degreeUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        离职证明
        String dimissionUrl = memberEmpBpmUpdateVo.getDimissionUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 4));
        if (!StringUtils.isEmpty(dimissionUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(4); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("离职证明");
            imgUrlEntity.setUrl(dimissionUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }

//        体检报告
        String healthUrl = memberEmpBpmUpdateVo.getHealthUrl();
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 5));
        if (!StringUtils.isEmpty(healthUrl)) {
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setType(5); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告
            imgUrlEntity.setOid(id);
            imgUrlEntity.setName("体检报告");
            imgUrlEntity.setUrl(healthUrl);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlService.saveE(imgUrlEntity);
        }
//        身份证
        List<String> idcardImgs = memberEmpBpmUpdateVo.getIdcardImgs();
        if (!CollectionUtils.isEmpty(idcardImgs)) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 6));
            for (String idcardImg : idcardImgs) {
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setType(6); //0:流水，1：头像，2：毕业证,3:学位证，4：离职证明,5：体检报告,6:身份证正反面
                imgUrlEntity.setOid(id);
                imgUrlEntity.setName("身份证");
                imgUrlEntity.setUrl(idcardImg);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlService.saveE(imgUrlEntity);
            }

        }
//        return id;
    }


    public static void main(String[] args) {

        System.out.println("select \n" +
                "C_OID,\n" +
                "C_CODE,\n" +
                "C_NAME,\n" +
                "C_HIREDATE,\n" +
                "C_ORGNAME,\n" +
                "C_UNITNAME,\n" +
                "C_JOBNAME,\n" +
                "C_EMPLOYEESTATUS,\n" +
                "C_IDCARD,\n" +
                "C_RECORDTIME,\n" +
                "C_HIREINFO,\n" +
                "C_ORGID,\n" +
                "C_UNITID,\n" +
                "C_JOBID,\n" +
                "C_CENTERPEOPLE,\n" +
                "C_PETPEOPLE,\n" +
                "C_MYPHONE,\n" +
                "C_EMAIL\n" +
                "from tb_inf_employee e  with(nolock)\n" +
                "left join (select c_recordtime,C_EMPOID from tb_per_staffrecord with(nolock) where C_RECORDTYPE in (4,6,5,8)) s on s.C_EMPOID = e.C_EMPLOYEEID\n" +
                "where 1=1\n" +
                "and C_IDCARD=");
    }


    /**
     * 是否是负责人
     *
     * @param request
     * @param oid
     * @return
     * @throws Exception
     */
    private boolean isPrincipalUser(HttpServletRequest request, Long oid) throws Exception {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String userCode = user.getString("usercode");
        if (userCode.equals(employeeInfoEntity.getPrincipalUserCode())) {
            return true;
        } else {
            return false;
        }
    }


    private void setArgs(EmployeeBpmEntity bpmEntity, EmployeeBpmDto employeeBpmDto) {
        Long orgId = bpmEntity.getOrgId();
        String orgNameById = jobController.getOrgNameById(orgId);
        employeeBpmDto.setOrgname(orgNameById);

//        部门
        Long unitId = bpmEntity.getUnitId();
        String unitname = jobController.getOrgNameById(unitId);
        employeeBpmDto.setUnitname(unitname);
//        职级
        Long jobLevelId = bpmEntity.getJobLevelId();
        String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
        employeeBpmDto.setJobLevel(jobLevelNameById);
//        岗位
        Long jobId = bpmEntity.getJobId();
        String jobName = jobController.getJobName(jobId);
        employeeBpmDto.setJobname(jobName);

//        原公司
        Long oldCompanyId = bpmEntity.getOldCompanyId();
        String oldCompany = jobController.getOrgNameById(oldCompanyId);
        employeeBpmDto.setOldCompany(oldCompany);
//        原部门
        Long oldDepId = bpmEntity.getOldDepartmentId();
        String oldDep = jobController.getOrgNameById(oldDepId);
        employeeBpmDto.setOldDepartment(oldDep);
//        原职级
        Long oldJobLevelId = bpmEntity.getOldJobLevelId();
        String oldJobLevel = jobController.getJobLevelNameById(oldJobLevelId);
        employeeBpmDto.setOldJobLevel(oldJobLevel);
//        原岗位
        Long oldJobId = bpmEntity.getOldJobId();
        String oldJobName = jobController.getJobName(oldJobId);
        employeeBpmDto.setOldJobName(oldJobName);
    }

    //专业类型获取树形
    public List<Map<String, Object>> finOrgByPid(List<professionstyleDto> professionstyleDtoList, String pid) {
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        for (professionstyleDto professionstyleDto : professionstyleDtoList) {
            if (professionstyleDto.getCparantid().equals(pid)) {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("value", professionstyleDto.getCcode());
                hashMap.put("label", professionstyleDto.getCname());
                List<Map<String, Object>> childrenList = finOrgByPid(professionstyleDtoList, professionstyleDto.getCcodeitem());
                if (!CollectionUtils.isEmpty(childrenList))
                    hashMap.put("children", childrenList);
                arrayList.add(hashMap);
            }
        }
        return arrayList;
    }

    public String ListToString(ArrayList<String> fileUrlList) {
        String Url = "";
        for (String s : fileUrlList) {
            Url += s + ",";
        }
        return Url.substring(0, Url.length() - 1);
    }

    /**
     * 同步企业微信用户到employee表
     */
    @GetMapping ("/syncQwToEmp")
    public R syncQwToEmp() {
        List<QwUserEntity> qwUserEntityList = qwUserDao.selectList(null);
        List<EmployeeInfoEntity> employeeInfoEntities=new ArrayList<>();
        List<Object> collect = qwUserEntityList.stream().map(item -> {
            EmployeeInfoEntity employeeInfoEntity = new EmployeeInfoEntity();
            BeanUtil.copyProperties(item, employeeInfoEntity);
            return null;
        }).collect(Collectors.toList());
        return null;
    }

}
